package co.yixiang.huiMin.controller;



import cn.hutool.core.map.MapUtil;
import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.huiMin.entity.YxStoreCart;
import co.yixiang.huiMin.entity.YxStoreOrder;
import co.yixiang.huiMin.entity.YxStoreProduct;
import co.yixiang.huiMin.mapper.YxStoreProductMapper;
import co.yixiang.huiMin.service.YxStoreCartService;
import co.yixiang.huiMin.service.YxStoreOrderService;
import co.yixiang.modules.shop.domain.ProductBrand;
import co.yixiang.modules.shop.repository.ProductBrandRepository;
import co.yixiang.modules.shop.service.mapper.ProductBrandMapper;
import co.yixiang.modules.utils.MapUtils;
import co.yixiang.modules.utils.TenpayHttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author Author
 * @since 2020-07-04
 */
@RestController

@Api(tags = "订单")
@RequestMapping("/yxStoreOrder")
public class YxStoreOrderController {
    @Resource
    private YxStoreOrderService yxStoreOrderService;

    @Resource
    private TenpayHttpClient tenpayHttpClient;
    @Resource
    private YxStoreCartService yxStoreCartService;

    @Resource
    private YxStoreProductMapper yxStoreProductMapper;

    @Resource
    private ProductBrandRepository productBrandRepository;


    @ApiOperation("查询订单详情")
    @AnonymousAccess
    @GetMapping("inquiryOrderInfo")
    public ResponseEntity inquiryOrderInfo(String orderId){
        YxStoreOrder storeOrder = yxStoreOrderService.getOne(new QueryWrapper<YxStoreOrder>().eq("order_id", orderId));
        Map<String, Object> objectHashMap = new HashMap<>();
        ArrayList<Map<String, Object>> resultMapList = new ArrayList<>();
        if (storeOrder!=null){
            String[] split = storeOrder.getCartId().split(",");
            List<Integer> collect = Arrays.stream(split).mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
            List<YxStoreCart> yxStoreCart = yxStoreCartService.list(new QueryWrapper<YxStoreCart>().in("id",  collect));
            for (YxStoreCart storeCart : yxStoreCart) {
                Integer productId = storeCart.getProductId();
                YxStoreProduct yxStoreProduct = yxStoreProductMapper.selectById(productId);
                Map<String, Object> map = new HashMap<>();
                //map.putAll(MapUtils.entityToMap(yxStoreProduct));
                map.put("storeCart",storeCart);
                Integer brandId = yxStoreProduct.getBrandId();
                Optional<ProductBrand> byId = productBrandRepository.findById(brandId);



                ProductBrand productBrand = byId.get();
                Map<String, Object> map1 = MapUtils.entityToMap(yxStoreProduct);
                map1.put("bandName",productBrand.getName());
                map1.put("shopName",productBrand.getName());
                map.put("storeProduct",map1);
                resultMapList.add(map);
            }
            objectHashMap.put("store",resultMapList);
            objectHashMap.put("order",storeOrder);

        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code",200);
        stringObjectHashMap.put("message",objectHashMap);
        return ResponseEntity.ok(stringObjectHashMap);
    }

    @ApiOperation("修改订单状态")
    @PostMapping("changeOrderStatus")
    public ResponseEntity changeOrderStatus(String orderId,Integer status){
        YxStoreOrder storeOrder = yxStoreOrderService.getOne(new QueryWrapper<YxStoreOrder>().eq("order_id", orderId));
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("message","订单不存在");
        if(storeOrder != null){
            stringObjectHashMap.put("code",200);
            storeOrder.setStatus(status);
            if (yxStoreOrderService.updateById(storeOrder)) stringObjectHashMap.put("message","修改成功");else
                stringObjectHashMap.put("message","修改失败");
            return ResponseEntity.ok(stringObjectHashMap);
        }
        stringObjectHashMap.put("code",500);
        return ResponseEntity.ok(stringObjectHashMap);
    }

    @ApiOperation("退款")
    @PostMapping("refundOrder")
    public ResponseEntity refundOrder(String orderId){
        YxStoreOrder storeOrder = yxStoreOrderService.getOne(new QueryWrapper<YxStoreOrder>().eq("order_id", orderId));


        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("message","订单不存在");
        if(storeOrder != null){
            try {
                JSONObject jsonObject;
                if (storeOrder.getPayType() == null) {
                    stringObjectHashMap.put("code",300);
                    stringObjectHashMap.put("message","未交易");
                    return ResponseEntity.ok(stringObjectHashMap);
                }
                switch (Integer.parseInt(storeOrder.getPayType())) {
                    case 1:
                        //支付宝
                        System.out.println(tenpayHttpClient.callHttpPost("http://47.103.22.134:8080/aliPay/refund", String.format("orderId=%s&reason=退款",orderId)));
                        jsonObject = JSON.parseObject(tenpayHttpClient.getResContent());
                        break;
                    case 2:
                        System.out.println(tenpayHttpClient.callHttpPost("http://47.103.22.134:8080/weChatPay/refund", String.format("orderId=%s&reason=退款",orderId)));
                        jsonObject = JSON.parseObject(tenpayHttpClient.getResContent());
                        break;
                    default: throw new Exception("未知退款方式");
                }
                Object status = jsonObject.get("status");
                if (status!=null && status.equals("200")) {
                    stringObjectHashMap.put("code",200);
                    storeOrder.setStatus(-3);
                }
                if (yxStoreOrderService.updateById(storeOrder)) {
                    stringObjectHashMap.put("message", "修改成功");
                    return ResponseEntity.ok(stringObjectHashMap);
                }
                stringObjectHashMap.put("message","修改失败");
                return ResponseEntity.ok(stringObjectHashMap);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                stringObjectHashMap.put("message",e.getMessage());
            }

        }
        stringObjectHashMap.put("code",500);

        return ResponseEntity.ok(stringObjectHashMap);
    }


    @ApiOperation("查询首页统计")
    @AnonymousAccess
    @GetMapping("selectMassages")
    public ResponseEntity selectMassages(String merId){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code",200);

        stringObjectHashMap.put("message",yxStoreOrderService.selectMassages(merId));
        return ResponseEntity.ok(stringObjectHashMap);
    }



    @ApiOperation("查询待处理事务")
    @AnonymousAccess
    @GetMapping("selectYxStoreOrders")
    public ResponseEntity selectYxStoreOrders(String merId){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code",200);
         List<YxStoreOrder> list=yxStoreOrderService.selectYxStoreOrders(merId);
         //未付款
        long noPay = list.stream().map(v -> v.getPaid().equals(false)).count();
        //订单状态
        Map<Integer, Long> collect = list.stream().filter(v -> v.getPaid().equals(true)).collect(Collectors.groupingBy(YxStoreOrder::getStatus, Collectors.counting()));
        collect.put(-4,noPay);
        Map<String,Object> maps=new HashMap<>();
        //待付款
        maps.put("noPay",collect.get(-4) == null?0:collect.get(-4));
        //待发货
        maps.put("deliver",collect.get(0)== null?0:collect.get(0));
        //已收货
        maps.put("received",collect.get(2)== null?0:collect.get(2));
        //待收货
        maps.put("noReceive",collect.get(1)== null?0:collect.get(1));
        //申请退款
        maps.put("refund",collect.get(-1)== null?0:collect.get(-1));
        stringObjectHashMap.put("message",maps);
        return ResponseEntity.ok(stringObjectHashMap);
    }
}

